<?php
namespace app\api\controller\wsgoods;
use x\my\pay\Alipay;
use x\my\KdApi;
use x\my\Pay;
class Ordergoods extends Base{

    public function __construct() {
        parent::__construct();
        $this->checkLogin();
    }

    //添加订单
    function add(){
        $d = $this->post();
        $rule = [
            'goods_price_ids' => 'require',
            'address_id' => 'require',
            'pay_money' => 'require',
            'pay_type' => 'require',
        ];
        $msg = [
            'goods_price_ids.require' => '未选中商品',
            'address_id.require' => '未选择收货地址',
            'pay_money.require' => '支付金额必填',
            'pay_type.require' => '支付方式必填',
        ];
        check($rule, $msg, $d);
        if(isset($d["spassword"]) && !empty($d["spassword"])){
            $this->checkSPassword();
        }
        $goods_price_ids = $d['goods_price_ids'];
        $goods = [];
        foreach(explode(',',$goods_price_ids) as $v){
            $arr = explode('|', $v);
            $goods[$arr[0]] = $arr[1];
        }
        $invitecode=$d['invitecode'];
        $order_nos = s("orderGoods", "c")->add($this->userinfo['id'], $d['address_id'], $goods,$invitecode,$d['isUsepoints'],$d['totalPoint'], $d['note']);
        if(!$order_nos) err(s("orderGoods", "c")->getError());

        //在线支付
        if($d['pay_money']){
            //充值余额
            $recharge_order_no = m('recharge', 'c')->add($this->userinfo['id'], $d['pay_money'], $d['pay_type'],'在线购买','order_goods',0,implode(',',$order_nos));
            if(!$recharge_order_no) err(m("recharge", "c")->getError());
            #充值信息
            $recharge_info = $this->db->query("select * from recharge where order_no=?",[$recharge_order_no],1);
            $total_fee = bcmul($recharge_info['money'],100,0);

            #微信 #4 统一下单
            if($d['pay_type']==0){
                $rs = [];
                #开放平台->移动应用->商户号
                if(in_array($d['partner'],[5100,5200])){
                    $config = [
                        'appid' => c('api.wx_app_appid'),
                        'mch_id' => c('api.wx_app_mchid'),
                        'key'    => c('api.wx_app_key'),
                        'mode'   => 'optional',
                    ];
                    $pay = Pay::wechat($config);
                    $order = [
                        'body' => '在线购买',
                        'out_trade_no' => $recharge_info['order_no'],
                        'total_fee' => $total_fee,
                        'notify_url' => url('notice/wxrecharge'),
                        'trade_type' => 'APP',
                    ];
                    $rs = $pay->app($order)->getContent();
                    $rs = json_decode($rs,true);
                    $data = [
                        'appid'=>$rs['appid'],
                        'partnerid'=>$rs['partnerid'],
                        'prepayid'=>$rs['prepayid'],
                        'package' => $rs['package'],
                        'noncestr'=> $rs['noncestr'],
                        'timestamp'=>$rs['timestamp'],
                        'sign' => $rs['sign'],
                        'order_no'=>$recharge_info['order_no'],
                    ];
                    //$data['sign'] = Pay::sign($data);
                    suc($data);
                    #h5 支付
                }else if(in_array($d['partner'],[5300,5400])){
                    $config = [
                        'appid' => c('api.wx_app_appid'),
                        'mch_id' => c('api.wx_app_mchid'),
                        'key'    => c('api.wx_app_key'),
                        'mode'   => 'optional',
                    ];
                    $pay = Pay::wechat($config);
                    $order = [
                        'body' => '在线购买',
                        'out_trade_no' => $recharge_info['order_no'],
                        'total_fee' => $total_fee,
                        'notify_url' => url('notice/wxrecharge'),
                        'trade_type' => 'APP',
                    ];
                    $rs = $pay->app($order)->getContent();
                    $rs = json_decode($rs,true);
                    $data = [
                        'appid'=>$rs['appid'],
                        'partnerid'=>$rs['partnerid'],
                        'prepayid'=>$rs['prepayid'],
                        'package' => $rs['package'],
                        'noncestr'=> $rs['noncestr'],
                        'timestamp'=>$rs['timestamp'],
                        'sign' => $rs['sign'],
                        'order_no'=>$recharge_info['order_no'],
                    ];
                    //$data['sign'] = Pay::sign($data);
                    suc($data);
                    #小程序支付
                }else if(in_array($d['partner'],[5500])){
                    if(!isset($d['openid'])) err('openid 不能为空');
                    $config = [
                        #开放平台->移动应用->商户号->授权小程序
                        'miniapp_id' => c('api.wx_xcx_appid'),
                        'mch_id' => c('api.wx_pay_mchid'),
                        'key' => c('api.wx_pay_key'),
                        'mode'   => 'optional',
                    ];
                    $pay = Pay::wechat($config);
                    $order = [
                        'out_trade_no' => $recharge_info['order_no'],
                        'body'      => '在线购买',
                        'total_fee' => $total_fee,
                        'openid'    => $d['openid'],
                        'notify_url' => url('notice/wxrecharge'),
                    ];
                    $rs = $pay->miniapp($order);
                    suc($rs);
                }
                #支付宝
            }else if($d['pay_type']==1){
                err('支付宝支付,暂未开放');
            }
            //直接付
        }else{
            foreach ($order_nos as $value) {
                $pay_rs = s("orderGoods", "c")->pay($value);
            }
            suc();
        }
    }
    /**
     * 我的订单, 支付我的订单
     * @return [type] [description]
     */
    public function continuePay(){
        $d = $this->post();
        $rule = [
            'order_no' => 'require',
            'pay_type' => 'require',
        ];
        $msg = [
            'order_no.require' => '订单编号必须填写',
            'pay_type.require' => '支付类型必须填写',
        ];
        check($rule, $msg, $d);
        $rs = s('OrderGoods','c')->pay($d['order_no']);
        if($rs===true) suc();
        if($rs===false) err(s('OrderGoods','c')->getError());
        //在线支付
        if($rs<0){
            $money = 0-$rs;
            $recharge_order_no = m('recharge', 'c')->add($this->userinfo['id'],$money, $d['pay_type'],'在线购买','order_goods',0,$d['order_no']);
            if(!$recharge_order_no) err(m("recharge", "c")->getError());
            #充值信息
            $recharge_info = $this->db->query("select * from recharge where order_no=?",[$recharge_order_no],1);
            $total_fee = bcmul($recharge_info['money'],100,0);

            #微信 #4 统一下单
            if($d['pay_type']==0){
                $rs = [];
                #开放平台->移动应用->商户号
                if(in_array($d['partner'],[5100,5200])){
											$config = [
													'appid' => c('api.wx_app_appid'),
													'mch_id' => c('api.wx_app_mchid'),
													'key'    => c('api.wx_app_key'),
													'mode'   => 'optional',
											];
											$pay = Pay::wechat($config);
											$order = [
													'body' => '在线购买',
													'out_trade_no' => $recharge_info['order_no'],
													'total_fee' => $total_fee,
													'notify_url' => url('notice/wxrecharge'),
													'trade_type' => 'APP',
											];
											$rs = $pay->app($order)->getContent();
											$rs = json_decode($rs,true);
											$data = [
													'appid'=>$rs['appid'],
													'partnerid'=>$rs['partnerid'],
													'prepayid'=>$rs['prepayid'],
													'package' => $rs['package'],
													'noncestr'=> $rs['noncestr'],
													'timestamp'=>$rs['timestamp'],
													'sign' => $rs['sign'],
													'order_no'=>$recharge_info['order_no'],
											];
											//$data['sign'] = Pay::sign($data);
											suc($data);
                    #h5 支付
                }else if(in_array($d['partner'],[5300,5400])){
                    err('h5支付 暂未开放');
                    #小程序支付
                }else if(in_array($d['partner'],[5500])){
                    if(!isset($d['openid'])) err('openid 不能为空');
                    $config = [
                        #开放平台->移动应用->商户号->授权小程序
                        'miniapp_id' => c('api.wx_xcx_appid'),
                        'mch_id' => c('api.wx_pay_mchid'),
                        'key' => c('api.wx_pay_key'),
                        'mode'   => 'optional',
                    ];
                    $pay = Pay::wechat($config);
                    $order = [
                        'out_trade_no' => $recharge_info['order_no'],
                        'body'      => '在线购买',
                        'total_fee' => $total_fee,
                        'openid'    => $d['openid'],
                        'notify_url' => url('notice/wxrecharge'),
                    ];
                    $rs = $pay->miniapp($order);
                    suc($rs);
                }
                #支付宝
            }else if($d['pay_type']==1){
                err('支付宝支付,暂未开放');
            }
        }
    }

    //确认收货
    public function finish(){
        $d = $this->post;
        $rule = [
            'order_no'=>'require',
        ];
        $msg = [
            'order_no.require' => '订单编号不能为空',
        ];
        check($rule,$msg,$d);
        $rs = s('OrderGoods','c')->finish($this->userinfo['id'],$d['order_no']);
        if ($rs) {
            suc('完成收货!');
        }else{
            err(s('OrderGoods','c')->getError());
        }

    }

    //申请退款
    public function applyRefund(){
        $d = $this->post();
        $rule = [
            'order_id'=>'require',
        ];
        $msg = [
            'order_id.require' => '订单ID不能为空',
        ];
        check($rule,$msg,$d);
        if(!isset($d['order_id'])){
            err("参数错误!");
        }
        $info = $this->db->query('select * from order_goods where id=? and user_id=?',[$d['order_id'],$this->userinfo['id']],1);
        if(!$info){
            err("订单不存在!");
        }
        $m = m('orderGoods','c');
        $rs = $m->apply_refund($d['order_id']);
        if($rs){
            suc('退款申请已提交!');
        }else{
            err($m->getError());
        }

    }

    //订单详情
    public function detail(){
        $d = $this->post;
        $rule = [
            'order_no'=>'require',
        ];
        $msg = [
            'order_no.require' => '订单编号不能为空',
        ];
        check($rule,$msg,$d);
        $order = $this->db->query('select * from order_goods_no where order_no=? and user_id=?',[$d['order_no'],$this->userinfo['id']],1);
        if (!$order) suc();
        $order['create_time'] = com_time_format($order["create_time"]);
        $order['fh_time'] = com_time_format($order["fh_time"]);
        $order['last_sh_time'] = com_time_format($order["last_sh_time"]);
        $order['pay_time'] = com_time_format($order["pay_time"]);
        $order['pj_time'] = com_time_format($order["pj_time"]);
        $order['refund_time'] = com_time_format($order["refund_time"]);
        #订单列表
        $order_goods = $this->db->query("select a.*,IFNULL(b.username,'') as shopname,c.postage from order_goods a left join shop b on a.shop_id=b.id left join goods c on a.goods_id=c.id where a.user_id=? and a.order_no=? order by a.id desc",[$this->userinfo['id'],$d['order_no']]);

        $total_postage = 0;
        foreach ($order_goods as $v) {
            $total_postage += bcmul($v['postage'],$v['nums']);
        }
        $order['total_postage'] = $total_postage;

        #物流
        $wuliu = [];
        if ($order['status']>2) {
            $wuliu = KdApi::getOrderTracesByJson($order_goods['0']['kd_code'],$order_goods['0']['kd_no']);
            $wuliu = json_decode($wuliu,true);
            if ($wuliu && $wuliu['Success']==true) {
                $wuliu['Traces'] = array_reverse($wuliu['Traces']);
            }
        }
        if (!$wuliu) {
            $wuliu = (object)$wuliu;
        }

        $data = [
            'orderstatus' => $order,
            'goods' => $order_goods,
            'kd'=>$wuliu
        ];
        suc($data);
    }

    //订单删除
    public function delete(){
        $d = $this->post;
        $rule = [
            'order_no'=>'require',
        ];
        $msg = [
            'order_no.require' => '订单编号不能为空',
        ];
        check($rule,$msg,$d);

        $rs = s('OrderGoods','c')->delete($this->userinfo['id'],$d['order_no']);
        if ($rs) {
            suc('删除成功!');
        }else{
            err(s('OrderGoods','c')->getError());
        }
    }


    //物流查看
    public function findLogistical(){
        $d = $this->post();
        $rule = [
            'kd_code'=>'require',
            'kd_no'=>'require',
        ];
        $msg = [];
        check($rule,$msg,$d);
        $field = [
            'id',
            'user_id',
            'goods_price_id',
            'goods_id',
            'title',
            'goods_price_title',
            'goods_price_price',
            'pic',
            'nums',
            'sh_name',
            'sh_address',
            'sh_phone',
            'kd_no',
            'kd_name',
        ];
        $field = implode(",", $field);
        $list = $this->db->query("select {$field} from order_goods where kd_code=? and kd_no=? and user_id=?",[$d['kd_code'],$d['kd_no'],$this->userinfo['id']]);
        if(!$list){
            err("订单不存在!");
        }

        $rs = KdApi::getOrderTracesByJson($d['kd_code'],$d['kd_no']);
        $wuliu = json_decode($rs,true);
        if ($wuliu && $wuliu['Success']==true) {
            $wuliu['Traces'] = array_reverse($wuliu['Traces']);
        }
        $data = [
            'order_list'=>$list,
            'kd'=>$wuliu,
        ];
        suc($data);
    }

    //积分列表
    public function pointList(){
        $d = $this->post;
        $rule = [
            'page'=>'require|integer',
            'limit'=>'require|integer',
        ];
        $msg = [
            'page.require' => 'page不能为空',
            'limit.require' => 'limit不能为空',
        ];
        check($rule,$msg,$d);

        $map = [];
        $map[] = ["and","user_id","=",$this->userinfo["id"]];
        $map[] = ["and","sh_status",">",0];
        $map[] = ["and","total_point",">",0];
        $w = where($map);
        $rs = $this->db->query("select * from order_goods {$w[0]} order by id desc".limit($d['page'],$d['limit']),$w[1],'',true);
        $info = $this->db->query("select sum(total_point) total_point from order_goods {$w[0]}",$w[1],1);
        if($rs){
            foreach ($rs[0] as $k => $v) {
                $rs[0][$k]['create_time_name'] = com_time_format($v["create_time"]);
            }
            $total_point = $info['total_point']?$info['total_point']:'0';
            suc(['lists'=>$rs[0],'total_point'=>$total_point],$rs[1]);
        }
        suc(['lists'=>[],'total_point'=>0],0);
    }

    //售出订单 - 我的下级代理商
    public function sold(){
        $d = $this->post();
        $rule = [
          'page'=>'require|integer',
          'limit'=>'require|integer',
        ];
        $msg = [];
        check($rule,$msg,$d);

        $myson = m('User','c')->myson($this->userinfo['id'],[4]);

        $map = [];
        if ($myson['user_ids']) {
            $map[] = ["and","user_id","in",$myson['user_ids']];
        }else{
            $map[] = ["and","user_id","in",[0]];
        }

        //找本月
        $month_time = month_time($d['ym']);

        $map[] = ["and","create_time",">=",$month_time['start_time']];
        $map[] = ["and","create_time","<=",$month_time['end_time']];
        $w = where($map);
        $sql = "select id,order_no,user_id,order_total_money,status,create_time,title,goods_price_title,pic from order_goods_no $w[0] order by id desc ".limit($d['page'],$d['limit']);
        $list = $this->db->query($sql,$w[1],'',true);

        foreach ($list[0] as $k=>$v) {
            foreach ($myson['user_name'] as $key => $val) {
                if ($key == $v['user_id']) $list[0][$k]['name'] = $val;
            }
            $list[0][$k]['create_time_name'] = com_time_format($v["create_time"]);
        }
        suc(['list'=>$list[0],$list[1],'ym'=>date("Y-m",strtotime('-1 month',strtotime(date('Ym01',$month_time['start_time']))))]);
    }
}
?>
